require "Common/define"
require "Logic/Config"
require "Common/functions"
require "View/HomeUI/UINotice"

UIHeadMenu = {};
HelperFunc.SetUIEnv(UIHeadMenu)
local this = UIHeadMenu;
--玩家信息控件变量

this.text_money = nil;
this.text_bigbao = nil; ---钻石
this.text_power = nil;
this.btn_back = nil;
this.img_Icon = nil;
this.txt_name = nil;
this.txt_level = nil;
this.btn_head = nil;
this.exp = nil;
this.goldPar = nil;
this.expPar = nil;
this.diamPar = nil;
this.frame = nil;
this.cashIcon = nil;
this.coinIcon = nil;
this.frameId = nil;
this.particles = nil;
this.drawWrappers = nil;
this.config = nil;
this.hasInit = false;
this.particle = nil;
this.btn_vip = nil
--控制器
this.ctrlNotice = nil;
this.btnPower = nil
this.allPower = nil
this.showPowerDetailCtrl = nil
this.mainPower = nil

function UIHeadMenu.Init(isNoticeDown)
    this.isNoticeDown = isNoticeDown
    config = G.dataTable["t_item"];
    local name, package = getUIName(PanelResNames.UIHeadMenu);
    panelMgr:ShowUI(name, package, this.onCreate, Config.useLocalUI);
end
function UIHeadMenu.SetNoticeDown(isNoticeDown)
    this.isNoticeDown = isNoticeDown or false
    if ctrlNotice then
        ctrlNotice.selectedIndex = this.isNoticeDown and 1 or 0
    end
end
--定义控件
function UIHeadMenu.onCreate(obj)
    --设置ui在最上层，控件可以点击
    if not hasInit then
        panelMgr.ShowFadeEff(obj);
        --controllerState = obj:GetController("state");
        text_power = obj:GetChild("text_power");
        cashIcon = obj:GetChild("CashLb");
        this.cashAdd = cashIcon:GetChild("add");
        this.cashJump = cashIcon:GetChild("btnJump");
        coinIcon = obj:GetChild("CoinLb");
        this.coinAdd = coinIcon:GetChild("add");
        this.coinJump = coinIcon:GetChild("btnJump");
        text_bigbao = obj:GetChild("CoinLb"):GetChild("title");
        text_money = obj:GetChild("CashLb"):GetChild("title");
        --btn_back = obj:GetChild("BackBtn");
        btn_head = obj:GetChild("Head");
        --img_Icon = btn_head:GetChild("icon");
        img_Icon = btn_head:GetChild("head"):GetChild("HeadIcon");
        --frame = obj:GetChild("frame");
        frame = btn_head:GetChild("frame");
        particle = obj:GetChild("particle");
        txt_name = obj:GetChild("Name");
        txt_level = obj:GetChild("Level");
        exp = obj:GetChild("exp")
        goldPar = obj:GetChild("goldparticle");
        expPar = obj:GetChild("expparticle");
        diamPar = obj:GetChild("diamparticle");
        ctrlNotice = obj:GetController("c1")
        showProbablity=obj:GetController("hide");
        this.btnPower = obj:GetChild("n50")
        this.mainPower = obj:GetChild("text_power2")
        this.allPower = obj:GetChild("text_power_all")
        this.showPowerDetailCtrl = obj:GetController("ShowZhanli")
        this.BanClick = obj:GetController("BanClick")
        this.sourceUIobj = obj:GetChild("UISourceMultiple");
        this.showSourceController = obj:GetController("showSource")
        this.noticePanel = UINotice.New()
        this.noticePanel:OnCreate(obj:GetChild("HorseRaceLamp"))
        this.addEvent();
        hasInit = true
    end
    this.showPowerDetailCtrl.selectedIndex = 0
    text_power.text = HelperFunc.FormatResourceNum(logicMgr.HeroManager.GetHerosSumPower(), true)
    this.LocalListenEvent();
    this.freshRoleInfo();
    this.freshGameMoney();
    this.onShowBack(false);
    this.onShowHead();
    this.SetNoticeDown(this.isNoticeDown)
    logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UIHeadMenu,Config.FuncOpenType.RoleInfo, btn_head.name,btn_head);
    UIRedDots.addViewListen(PanelNames.UIHeadMenu,"UIHeadMenu" .. btn_head .name, btn_head, Config.RedDotsType.HeadAndFrame);
    UIRedDots.addViewListen(PanelNames.UIHeadMenu,"UIHeadMenu" .. btn_head .name, btn_head, Config.RedDotsType.VipWard);
    logicMgr.ItemFlyMgr.SetMoneyPos(this.cashIcon.x,this.cashIcon.y)
    logicMgr.ItemFlyMgr.SetDiamondPos(this.coinIcon.x,this.coinIcon.y)
    logicMgr.ItemFlyMgr.SetTeamExpPos(this.txt_level.x-this.txt_level.width,this.txt_level.y-this.txt_level.height)
    --InvasionHandler.ReqInitTeamBoss(0)
end

function UIHeadMenu.CLoseorOpen(flag)
    if flag then
        showProbablity.selectedIndex=0;
    else
        showProbablity.selectedIndex=1;
    end
end

function UIHeadMenu.OnDestroy()
    hasInit = false;
    ctrlNotice = nil
    drawWrappers = nil;
    if particles then
        destroyImmediate(particles);
    end
    particles = nil
    this.noticePanel:OnDestroy()
    this.removeEvent();
    HelperFunc.ClearParticles()
end

function UIHeadMenu.OnEnable()
    this.LocalListenEvent();
    if this.noticePanel then this.noticePanel:OnEnable() end
end

function UIHeadMenu.OnDisable()
    this.LocalCloseEvent();
    UIRedDots.removeViewEvent(PanelNames.UIHeadMenu);
    this.noticePanel:OnDisable()
end

function UIHeadMenu.addEvent()
    btn_head.onClick:Add(this.onClickHead);
    this.coinJump.onClick:Add(this.onClickCoinJump);
    this.cashJump.onClick:Add(this.onClickCashJump);
    this.coinAdd.onClick:Add(this.onClickCoinAdd);
    this.btnPower.onClick:Add(function()
        this.allPower.text = getNumString(logicMgr.HeroManager.GetHerosSumPower(true))
        this.mainPower.text = getNumString(logicMgr.HeroManager.GetHerosSumPower())
    end)
    --btn_back.onClick:Add( this.onClickBack);
end

function UIHeadMenu.removeEvent()
    --btn_back.onClick:Remove(this.onClickBack);
    btn_head.onClick:Remove(this.onClickHead);
    this.coinJump.onClick:Remove(this.onClickCoinJump);
    this.cashJump.onClick:Remove(this.onClickCashJump);
    this.coinAdd.onClick:Remove(this.onClickCoinAdd);
    this.btnPower.onClick:Clear()
end

function UIHeadMenu.LocalListenEvent()
    ListenEvent(Config.EventType.ReFreshHeroPower, this.SetInfo);
    ListenEvent(Config.EventType.Fresh_Currency, this.updateResource);
    ListenEvent(Config.EventType.Show_HeadUI_Back, this.onShowBack);
    ListenEvent(Config.EventType.Show_HeadMenu_HeadIcon, this.onShowHead);
    ListenEvent(Config.EventType.FreashRoleShowDraw, this.onShowHead)
    ListenEvent(Config.EventType.Fresh_Level, this.freshRoleInfo);
    ListenEvent(Config.EventType.Get_DropAward, this.DropWards);
    ListenEvent(Config.EventType.Refresh_Frame, this.InitFrameID)
    ListenEvent(Config.EventType.Fresh_Bag,this.updateSource);
    ListenEvent(Config.EventType.Fresh_BagUseItemBack, logicMgr.ItemManager.showGetItem);
    ListenEvent(Config.EventType.Close_Draw_Panel, this.OnCloseDrawPanel);
    ListenEvent(Config.EventType.Close_headMenu,this.CLoseorOpen);
    ListenEvent(Config.EventType.TouchAnyKey, this.onAnyKeyDown);
end

function UIHeadMenu.LocalCloseEvent()
    CloseEvent(Config.EventType.ReFreshHeroPower, this.SetInfo);
    CloseEvent(Config.EventType.Fresh_Currency, this.updateResource);
    CloseEvent(Config.EventType.Show_HeadUI_Back, this.onSetHeadUiActive);
    CloseEvent(Config.EventType.Show_HeadMenu_HeadIcon, this.onShowHead);
    CloseEvent(Config.EventType.FreashRoleShowDraw, this.onShowHead)
    CloseEvent(Config.EventType.Fresh_Level, this.freshRoleInfo);
    CloseEvent(Config.EventType.Get_DropAward, this.DropWards);
    CloseEvent(Config.EventType.Refresh_Frame, this.InitFrameID)
    CloseEvent(Config.EventType.Fresh_Bag,this.updateSource);
    CloseEvent(Config.EventType.Fresh_BagUseItemBack, logicMgr.ItemManager.showGetItem);
    CloseEvent(Config.EventType.Close_Draw_Panel, this.OnCloseDrawPanel)
    CloseEvent(Config.EventType.Close_headMenu,this.CLoseorOpen);
    CloseEvent(Config.EventType.TouchAnyKey, this.onAnyKeyDown);

    logicMgr.FuncOpenManager.removeStatusCtr(PanelNames.UIHeadMenu);
end

function UIHeadMenu.DropWards(msg)
    HelperFunc.FlyToHeadItemData(msg["itemList"], goldPar, diamPar, expPar);
end

--游戏货币
function UIHeadMenu.freshGameMoney(d)
    if not isOpenUI(PanelNames.UIDraw) then
        cashIcon.icon = "ui://ItemAtlas/"..CurrencyEnum.MONEY;
        coinIcon.icon = "ui://ItemAtlas/"..CurrencyEnum.GOLD;
        local _currentGoldStock = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.MONEY)
        local _currentDiamondStock = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD)

        -- TAManager.UserSet("current_gold_stock",_currentGoldStock)
        -- TAManager.UserSet("current_diamond_stock",_currentDiamondStock)

        TAManager.UserSet("current_gold",_currentGoldStock)
        TAManager.UserSet("current_diamond",_currentDiamondStock)

        text_money.text = getNumString(_currentGoldStock)
        text_bigbao.text = _currentDiamondStock;
        this.cashId = CurrencyEnum.MONEY;
        this.coinId = CurrencyEnum.GOLD;
    end
end

function UIHeadMenu.SetInfo()
    local power = logicMgr.HeroManager.GetHerosSumPower()
    local cur_power_str = HelperFunc.FormatResourceNum(power, true)
    if this.cur_poswer_content == nil or this.cur_poswer_content ~= cur_power_str then
        text_power.text = cur_power_str
        this.cur_poswer_content = cur_power_str

        logicMgr.TATrackCollect.Track_AllPower()

        -- iOS Widget: 战力更新
        if CompareOriginVersion("1.4.2.0001") then
            LoginSDK.GetInstance():SetWidgetUserPower(power)
        end
    end
end

--角色信息变化统计
function UIHeadMenu.freshRoleInfo()
    local att = G.serverData["roleInfo"];
    if att ~= nil then
        local level = att.show.level
        txt_level.text = level;
        local curExp = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.RoleExp);
        curExp = curExp == nil and 0 or curExp
        local cfg = dataTable.getRow("t_characterexp", MakeTopLevelId(level))
        if cfg == nil then
            logError("找不到t_characterexp  "..level)
            return
        end
        local maxExp = cfg.f_CharacterExp
        local value = curExp / maxExp
        if value >= 1 then
            value = 1;
        end
        exp.value = value * 100
    end
end

--刷新资源
function UIHeadMenu.updateResource()
    this.freshRoleInfo();
    this.freshGameMoney();
end

function UIHeadMenu.OnCloseDrawPanel()
    cashIcon.icon = "ui://ItemAtlas/"..CurrencyEnum.MONEY;
    coinIcon.icon = "ui://ItemAtlas/"..CurrencyEnum.GOLD;
    local _currentGoldStock = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.MONEY)
    local _currentDiamondStock = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD)

    -- TAManager.UserSet("current_gold_stock",_currentGoldStock)
    -- TAManager.UserSet("current_diamond_stock",_currentDiamondStock)

    text_money.text = getNumString(_currentGoldStock)
    text_bigbao.text = _currentDiamondStock;
    this.cashId = CurrencyEnum.MONEY;
    this.coinId = CurrencyEnum.GOLD;
end

function UIHeadMenu.onShowBack(bActive)
    --controllerState.selectedIndex = bActive and 1 or 0;
end

function UIHeadMenu.onClickHead()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.RoleInfo, true,btn_head) then
        AudioManager.Play(1024)
        showUI(PanelNames.UIHeadInfo);
    end
end

function UIHeadMenu.onClickCoinAdd()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Cost, true, this.coinAdd) then
        logicMgr.CostManager.gotoCostById();
    end
end

function UIHeadMenu.onClickCashAdd()
end

function UIHeadMenu.onClickCoinJump()
    --showUI(PanelNames.UISource, function ()
    --end, this.coinId);
    this.showSourceController.selectedIndex = 1;
    this.showSourceList = {this.coinId}
    this.updateSource();
end

function UIHeadMenu.onClickCashJump()
    --showUI(PanelNames.UISource, function ()
    --end, this.cashId);
    this.showSourceController.selectedIndex = 1;
    this.showSourceList = {this.cashId}
    this.updateSource();
end

function UIHeadMenu.updateSource()
    logicMgr.ItemManager.updateSourceUI(this.sourceUIobj, this.showSourceList, function ()
        this.showSourceController.selectedIndex = 0;
    end, function ()
        this.showSourceController.selectedIndex = 0;
        if this.goFunc then
            this.goFunc();
        end
    end );
end

function UIHeadMenu.onClickBack(obj)
    panelMgr:Pop(false, nil);
end

function UIHeadMenu.InitFrameID(msg)
    frameId = msg[1];
end

function UIHeadMenu.isNeedShowMask(flag)
    if flag then
        this.BanClick.selectedIndex = 1;
    else
        this.BanClick.selectedIndex = 0;
    end
end

function UIHeadMenu.isHaveShowMask()
    if this and this.BanClick and this.BanClick.selectedIndex == 1 then
        return true;
    end
    return false;
end

function UIHeadMenu.onAnyKeyDown()
    this.showPowerDetailCtrl.selectedIndex = 0
end

function UIHeadMenu.onShowHead()
    local myself = logicMgr.HeroManager.GetRoleInfo();
    if myself ~= nil then
        local _roleName = logicMgr.HeroManager.GetRoleName()
        local level = logicMgr.HeroManager.GetRoleLevel()

        TAManager.UserSet("role_name",_roleName)

        txt_name.text = _roleName
        this.freshRoleInfo()
        --[[txt_level.text = level
        local curExp = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.RoleExp);
        curExp = curExp == nil and 0 or curExp
        local cfg = dataTable.getRow("t_characterexp", level)
        if cfg == nil then
            logError("找不到t_characterexp  "..level)
            return
        end
        local maxExp = cfg.f_CharacterExp
        local value = curExp / maxExp
        if value >= 1 then
            value = 1;
        end
        exp.value = value * 100]]
        --local useSkinId = logicMgr.SkinManager.getHeroSkinId(HeroManager.GetRoleHeadID())
        --img_Icon.url = logicMgr.HeroManager.GetRoleIcon(useSkinId)

        local skinId = logicMgr.HeroManager.GetRoleInfo("pic")
        img_Icon.url = logicMgr.SkinManager.GetHeroIconBySkinId(skinId)
        SetHeadFEWithModelId(btn_head,HeroManager.GetRoleHeadID())

        local itemid = logicMgr.HeroManager.GetRoleInfo("picFrame")--frameId or logicMgr.HeroManager.GetRoleInfo("picFrame")
        frame.url = EnumConst.AtlasPath.ICONAtlas .. itemid;


        local frameID = decodeJsonStrToTabel(config[tostring(itemid)]["f_ItemFunction"])
        if frameID[2] ~= 0 then
            if (particles ~= nil) then
                destroyImmediate(particles);
                particles = nil
            end
            resMgr:LoadModelPrefab("Fx/EFF_Frame_" .. frameID[2], function(go)
                local drawWrapper = drawWrappers;
                if (drawWrapper == nil) then
                    drawWrapper = GoWrapper.New();
                    drawWrappers = drawWrapper
                end
                particles = newObject(go);
                particles.name = tostring(frameID[2]);
                particles:AddComponent(TCanvas);
                drawWrapper:SetWrapTarget(particles, false)
                particle.visible = true;
                particle:SetNativeObject(drawWrapper);
                Util.Lua_SetLocalPositionXYZ(particles.transform,0,0,0)
            end)
        end
    end
end

return UIHeadMenu;